<html lang="zh-CN"><head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>车辆费用记录</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        accent: '#F59E0B',
                        danger: '#EF4444',
                        dark: '#1F2937',
                        light: '#F3F4F6'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 10px 15px -3px rgba(0, 0, 0, 0.05), 0 4px 6px -2px rgba(0, 0, 0, 0.03)',
                        'card-hover': '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .transition-custom {
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }
            .scale-hover {
                transition: transform 0.3s ease, box-shadow 0.3s ease;
            }
            .scale-hover:hover {
                transform: translateY(-5px);
            }
            .error-border {
                border-color: #EF4444 !important;
            }
            .section {
                display: none;
            }
            .section.active {
                display: block;
                animation: fadeIn 0.3s ease-in-out;
            }
            .menu-item-active {
                color: #3B82F6 !important;
                position: relative;
            }
            .menu-item-active::after {
                content: '';
                position: absolute;
                bottom: -5px;
                left: 50%;
                transform: translateX(-50%);
                width: 6px;
                height: 6px;
                background-color: #3B82F6;
                border-radius: 50%;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-dark min-h-screen">
    <!-- 页面头部 -->
    <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-50 transition-custom">
<!--        <div class="container mx-auto px-4 py-3 flex justify-center items-center">
            <h1 class="text-xl font-bold text-primary text-center flex-1" id="pageTitle">车辆费用记录</h1>
        </div> -->
    </header>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 pt-16 pb-24">
        <!-- 错误提示区 -->
        <div id="errorContainer" class="hidden bg-danger/10 border border-danger/30 text-danger p-4 rounded-lg mb-6 animate-pulse">
            <p id="errorMessage"></p>
        </div>
        
        <!-- 新首页 section -->
        <section id="landingSection" class="section active pt-8">
            <div class="text-center mb-24 mt-4">
                <h2 class="text-[clamp(1.5rem,5vw,2rem)] font-bold text-gray-800 mb-2">欢迎回来</h2>
                <p class="text-gray-500">记录和管理您的车辆费用</p>
            </div>
            
            <!-- 功能卡片区域 - 优化手机显示，确保横向分布 -->
            <div class="grid grid-cols-3 gap-3 mb-8 px-1">
                <!-- 加油卡片 -->
                <div class="bg-white rounded-xl shadow-card p-3 scale-hover cursor-pointer flex flex-col items-center justify-between" id="fuelCard">
                    <div class="w-12 h-12 bg-yellow-100 rounded-xl flex items-center justify-center mb-2">
                        <i class="fas fa-gas-pump text-xl text-accent"></i>
                    </div>
                    <h3 class="text-sm font-bold text-gray-800 mb-1 text-center">加油记录</h3>
                    <button class="text-primary text-xs font-medium flex items-center mt-1">
                        记录 <i class="fas fa-arrow-right ml-1 text-xs"></i>
                    </button>
                </div>
                
                <!-- 过路费卡片 -->
                <div class="bg-white rounded-xl shadow-card p-3 scale-hover cursor-pointer flex flex-col items-center justify-between" id="tollCard">
                    <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center mb-2">
                        <i class="fas fa-road text-xl text-primary"></i>
                    </div>
                    <h3 class="text-sm font-bold text-gray-800 mb-1 text-center">过路费</h3>
                    <button class="text-primary text-xs font-medium flex items-center mt-1">
                        记录 <i class="fas fa-arrow-right ml-1 text-xs"></i>
                    </button>
                </div>
                
                <!-- 保养卡片 -->
                <div class="bg-white rounded-xl shadow-card p-3 scale-hover cursor-pointer flex flex-col items-center justify-between" id="maintenanceCard">
                    <div class="w-12 h-12 bg-green-100 rounded-xl flex items-center justify-center mb-2">
                        <i class="fas fa-wrench text-xl text-secondary"></i>
                    </div>
                    <h3 class="text-sm font-bold text-gray-800 mb-1 text-center">保养记录</h3>
                    <button class="text-primary text-xs font-medium flex items-center mt-1">
                        记录 <i class="fas fa-arrow-right ml-1 text-xs"></i>
                    </button>
                </div>
            </div>
            
            <!-- 快速统计 -->
            <div class="bg-white rounded-xl shadow-card p-4">
                <h3 class="text-base font-bold text-gray-800 mb-3">费用概览</h3>
                <div class="grid grid-cols-3 gap-2 text-center">
                    <div>
                        <p class="text-xs text-gray-500 mb-1">本月总支出</p>
                        <p class="text-lg font-bold text-primary" id="quickMonthTotal">¥0.00</p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-500 mb-1">加油总费用</p>
                        <p class="text-lg font-bold text-accent" id="quickFuelTotal">¥0.00</p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-500 mb-1">记录总数</p>
                        <p class="text-lg font-bold text-dark" id="quickRecordCount">0</p>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- 记录提报 section -->
        <section id="entrySection" class="section pt-6">
            <div class="flex items-center mb-6">
                <button id="backToHome" class="p-2 rounded-full hover:bg-gray-100 transition-custom mr-2">
                    <i class="fas fa-arrow-left text-gray-600"></i>
                </button>
                <h2 class="text-xl font-bold text-gray-800" id="entryTitle">添加加油记录</h2>
            </div>

            <!-- 记录表单 -->
            <div class="bg-white rounded-xl shadow-card p-5 mb-6 transform transition-all duration-300 hover:shadow-card-hover">
                <form id="expenseForm">
                    <input type="hidden" id="expenseType" value="fuel">
                    
                    <div class="mb-4">
                        <label for="date" class="block text-sm font-medium text-gray-700 mb-1">日期</label>
                        <input type="date" id="date" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom outline-none" required="">
                    </div>
                    
                    <!-- 里程记录字段 - 仅在加油和保养时显示 -->
                    <div id="odometerField" class="mb-4">
                        <label for="odometer" class="block text-sm font-medium text-gray-700 mb-1">当前里程 (公里)</label>
                        <input type="number" id="odometer" step="0.1" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom outline-none" required="">
                    </div>
                    
                    <!-- 加油特有字段 -->
                    <div id="fuelFields">
                        <div class="mb-4">
                            <label for="fuelType" class="block text-sm font-medium text-gray-700 mb-1">油品类型</label>
                            <select id="fuelType" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom outline-none" required="">
                                <option value="92">92号汽油</option>
                                <option value="95">95号汽油</option>
                                <option value="98">98号汽油</option>
                                <option value="diesel">柴油</option>
                                <option value="other">其他</option>
                            </select>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4 mb-4">
                            <div>
                                <label for="fuelAmount" class="block text-sm font-medium text-gray-700 mb-1">加油量 (升)</label>
                                <input type="number" id="fuelAmount" step="0.01" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom outline-none" required="">
                            </div>
                            <div>
                                <label for="fuelTotal" class="block text-sm font-medium text-gray-700 mb-1">总金额 (元)</label>
                                <input type="number" id="fuelTotal" step="0.01" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom outline-none" required="">
                            </div>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4 mb-4">
                            <div>
                                <label for="fuelPrice" class="block text-sm font-medium text-gray-700 mb-1">单价 (元/升)</label>
                                <input type="number" id="fuelPrice" step="0.01" min="0" class="w-full px-3 py-2 border border-gray-300 bg-gray-50 rounded-lg outline-none" readonly="">
                            </div>
                            <div>
                                <label for="fuelEfficiency" class="block text-sm font-medium text-gray-700 mb-1">油耗 (升/百公里)</label>
                                <input type="number" id="fuelEfficiency" step="0.01" min="0" class="w-full px-3 py-2 border border-gray-300 bg-gray-50 rounded-lg outline-none" readonly="">
                                <p id="efficiencyNote" class="text-xs text-gray-500 mt-1">* 需至少两次加油记录才能计算</p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 过路费特有字段 -->
                    <div id="tollFields" class="hidden">
                        <div class="mb-4">
                            <label for="tollAmount" class="block text-sm font-medium text-gray-700 mb-1">过路费金额 (元)</label>
                            <input type="number" id="tollAmount" step="0.01" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom outline-none" required="">
                        </div>
                        
                        <div class="mb-4">
                            <label for="tollPaymentMethod" class="block text-sm font-medium text-gray-700 mb-1">支付方式</label>
                            <select id="tollPaymentMethod" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom outline-none" required="">
                                <option value="etc">ETC</option>
                                <option value="wechat">微信支付</option>
                                <option value="alipay">支付宝</option>
                                <option value="cash">现金</option>
                                <option value="other">其他</option>
                            </select>
                        </div>
                        
                        <div class="mb-4">
                            <label for="tollStartLocation" class="block text-sm font-medium text-gray-700 mb-1">起点</label>
                            <input type="text" id="tollStartLocation" placeholder="出发收费站/路段" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom outline-none" required="">
                        </div>
                        
                        <div class="mb-4">
                            <label for="tollEndLocation" class="block text-sm font-medium text-gray-700 mb-1">终点</label>
                            <input type="text" id="tollEndLocation" placeholder="到达收费站/路段" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom outline-none" required="">
                        </div>
                    </div>
                    
                    <!-- 保养费特有字段 -->
                    <div id="maintenanceFields" class="hidden">
                        <div class="mb-4">
                            <label for="maintenanceAmount" class="block text-sm font-medium text-gray-700 mb-1">保养费用 (元)</label>
                            <input type="number" id="maintenanceAmount" step="0.01" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom outline-none" required="">
                        </div>
                        
                        <div class="mb-4">
                            <label for="maintenanceType" class="block text-sm font-medium text-gray-700 mb-1">保养类型</label>
                            <input type="text" id="maintenanceType" placeholder="例如：换机油、轮胎等" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom outline-none">
                        </div>
                    </div>
                    
                    <div class="mb-4">
                        <label for="notes" class="block text-sm font-medium text-gray-700 mb-1">备注</label>
                        <textarea id="notes" rows="2" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom outline-none" placeholder="添加备注信息..."></textarea>
                    </div>
                    
                    <button type="submit" id="saveButton" class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2.5 px-4 rounded-lg transition-custom flex justify-center items-center shadow-md hover:shadow-lg">
                        <i class="fas fa-save mr-2"></i> 保存记录
                    </button>
                </form>
            </div>
        </section>
        
        <!-- 历史记录 section -->
        <section id="historySection" class="section pt-6">
            <div class="flex items-center mb-5">
                <button id="backFromHistory" class="p-2 rounded-full hover:bg-gray-100 transition-custom mr-2">
                    <i class="fas fa-arrow-left text-gray-600"></i>
                </button>
                <h2 class="text-xl font-bold text-gray-800">历史记录</h2>
            </div>
            
            <div class="flex justify-between items-center mb-4 flex-wrap gap-2">
                <div class="relative w-full md:w-64">
                    <input type="text" id="searchRecords" placeholder="搜索记录..." class="pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom w-full">
                    <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                </div>
                <div class="flex space-x-2 overflow-x-auto pb-1">
                    <button id="filterAll" class="filter-btn active px-3 py-1.5 rounded-full text-sm bg-primary text-white whitespace-nowrap">全部</button>
                    <button id="filterFuel" class="filter-btn px-3 py-1.5 rounded-full text-sm bg-gray-200 whitespace-nowrap">加油</button>
                    <button id="filterToll" class="filter-btn px-3 py-1.5 rounded-full text-sm bg-gray-200 whitespace-nowrap">过路费</button>
                    <button id="filterMaintenance" class="filter-btn px-3 py-1.5 rounded-full text-sm bg-gray-200 whitespace-nowrap">保养</button>
                </div>
            </div>
            
            <div id="recordsList" class="space-y-3 max-h-[600px] overflow-y-auto pr-2">
                <!-- 记录将通过JavaScript动态添加 -->
                <div class="text-center text-gray-500 py-10">
                    <i class="fas fa-file-alt text-4xl mb-3 opacity-30"></i>
                    <p>暂无记录，添加您的第一条记录吧</p>
                </div>
            </div>
        </section>
        
        <!-- 统计 section -->
        <section id="statsSection" class="section pt-6">
            <div class="flex items-center mb-5">
                <button id="backFromStats" class="p-2 rounded-full hover:bg-gray-100 transition-custom mr-2">
                    <i class="fas fa-arrow-left text-gray-600"></i>
                </button>
                <h2 class="text-xl font-bold text-gray-800">费用统计</h2>
            </div>
            
            <div class="bg-white rounded-xl shadow-card p-5 mb-5">
                <div class="grid grid-cols-3 gap-3 mb-5">
                    <div class="bg-blue-50 p-3 rounded-lg">
                        <p class="text-xs text-blue-600">加油</p>
                        <p class="text-base font-bold" id="fuelTotalStats">0元</p>
                    </div>
                    <div class="bg-green-50 p-3 rounded-lg">
                        <p class="text-xs text-green-600">过路费</p>
                        <p class="text-base font-bold" id="tollTotalStats">0元</p>
                    </div>
                    <div class="bg-yellow-50 p-3 rounded-lg">
                        <p class="text-xs text-yellow-600">保养</p>
                        <p class="text-base font-bold" id="maintenanceTotalStats">0元</p>
                    </div>
                </div>
                
                <div class="mb-4">
                    <h4 class="font-medium text-sm mb-2">平均油耗</h4>
                    <div class="bg-gray-50 p-3 rounded-lg">
                        <p class="text-base font-bold text-primary" id="avgFuelEfficiency">-- 升/百公里</p>
                    </div>
                </div>
                
                <div class="mb-4">
                    <h4 class="font-medium text-sm mb-2">本月花费</h4>
                    <div class="bg-gray-50 p-3 rounded-lg">
                        <p class="text-base font-bold text-primary" id="monthTotalStats">0元</p>
                    </div>
                </div>
                
                <div>
                    <h4 class="font-medium text-sm mb-2">记录总数</h4>
                    <div class="bg-gray-50 p-3 rounded-lg">
                        <p class="text-base font-bold" id="totalRecordsStats">0</p>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- 设置 section -->
        <section id="settingsSection" class="section pt-6">
            <div class="flex items-center mb-5">
                <button id="backFromSettings" class="p-2 rounded-full hover:bg-gray-100 transition-custom mr-2">
                    <i class="fas fa-arrow-left text-gray-600"></i>
                </button>
                <h2 class="text-xl font-bold text-gray-800">应用设置</h2>
            </div>
            
            <div class="bg-white rounded-xl shadow-card p-5 mb-5">
                <h3 class="text-base font-bold mb-4 pb-2 border-b border-gray-100">数据管理</h3>
                
                <div class="space-y-3">
                    <button id="exportDataBtn" class="w-full flex justify-between items-center p-3 border border-gray-100 rounded-lg hover:bg-gray-50 transition-custom">
                        <span class="font-medium">导出数据</span>
                        <i class="fas fa-download text-primary text-lg"></i>
                    </button>
                    <button id="importDataBtn" class="w-full flex justify-between items-center p-3 border border-gray-100 rounded-lg hover:bg-gray-50 transition-custom">
                        <span class="font-medium">导入数据</span>
                        <i class="fas fa-upload text-primary text-lg"></i>
                    </button>
                    <input type="file" id="importFileInput" accept=".json" class="hidden">
                    <button id="clearAllDataBtn" class="w-full flex justify-between items-center p-3 border border-danger/20 rounded-lg hover:bg-danger/5 text-danger transition-custom">
                        <span class="font-medium">清空所有数据</span>
                        <i class="fas fa-trash-alt text-lg"></i>
                    </button>
                </div>
            </div>
            

            <div class="bg-white rounded-xl shadow-card p-5">
                <button id="aboutBtn" class="w-full flex justify-between items-center p-3 border border-gray-100 rounded-lg hover:bg-gray-50 transition-custom">
                    <span class="font-medium">关于车辆费用记录</span>
                    <i class="fas fa-info-circle text-primary text-lg"></i>
                </button>
            </div>
        </section>
    </main>

    <!-- 关于弹窗 -->
    <div id="aboutModal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden backdrop-blur-sm">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md mx-4 transform transition-all duration-300 scale-95 opacity-0" id="modalAboutContent">
            <div class="p-5 border-b border-gray-100 flex justify-between items-center">
                <h3 class="text-lg font-bold">关于车辆费用记录</h3>
                <button class="close-modal text-gray-500 hover:text-gray-700 p-2 rounded-full hover:bg-gray-100">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="p-5">
                <div class="text-center mb-5">
                    <div class="w-22 h-22 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-3">
                        <i class="fas fa-car text-6xl text-primary"></i>
                    </div>
                    <h4 class="text-base font-bold">车辆费用记录</h4>
                    <p class="text-gray-500 text-sm">版本 1.0.0</p>
                </div>
                
                <p class="text-gray-600 text-sm mb-3">
                    一款帮助您记录和管理车辆相关费用的应用，包括加油、过路费和保养等支出，让您更好地了解车辆使用成本。
                </p>
                
                <p class="text-gray-600 text-sm">
                    所有数据存储在本地设备上，保护您的隐私安全。
                </p>
            </div>
        </div>
    </div>

    <!-- 底部导航 -->
    <footer class="fixed bottom-0 left-0 right-0 bg-white shadow-lg border-t border-gray-100 py-2 px-5 z-40">
        <div class="flex justify-around">
            <button id="landingBtn" class="flex flex-col items-center menu-item-active">
                <i class="fas fa-home text-lg"></i>
                <span class="text-xs mt-1">首页</span>
            </button>
            <button id="historyBtn" class="flex flex-col items-center text-gray-500">
                <i class="fas fa-history text-lg"></i>
                <span class="text-xs mt-1">历史</span>
            </button>
            <button id="statsBtn" class="flex flex-col items-center text-gray-500">
                <i class="fas fa-chart-pie text-lg"></i>
                <span class="text-xs mt-1">统计</span>
            </button>
            <button id="settingsBtnHeader" class="flex flex-col items-center text-gray-500">
                <i class="fas fa-cog text-lg"></i>
                <span class="text-xs mt-1">设置</span>
            </button>
        </div>
    </footer>

    <script>
        // 全局错误处理
        window.addEventListener('error', function(error) {
            const message = `全局错误: ${error.message} 在 ${error.filename}:${error.lineno}`;
            showError(message);
        });
        
        window.addEventListener('unhandledrejection', function(event) {
            const message = `未捕获的Promise错误: ${event.reason?.message || event.reason}`;
            showError(message);
        });
        
        // 数据库配置
        const DB_CONFIG = {
            name: 'CarExpenseDB',
            version: 1,
            storeName: 'expenses'
        };
        
        // 全局数据库实例
        let db;
        
        // 初始化应用
        document.addEventListener('DOMContentLoaded', function() {
            try {
                // 初始化日期为今天
                const today = new Date().toISOString().split('T')[0];
                const dateInput = document.getElementById('date');
                if (dateInput) {
                    dateInput.value = today;
                }
                
                // 初始化数据库并设置事件监听
                initDB()
                    .then(() => {
                        // 数据库初始化成功后设置事件监听
                        setupEventListeners();
                        // 加载记录
                        return loadRecords();
                    })
                    .then(() => {
                        // 填充上次记录的里程
                        return populateLastOdometer();
                    })
                    .then(() => {
                        // 更新首页快速统计
                        return updateQuickStats();
                    })
                    .catch(error => {
                        showError('应用初始化失败: ' + error.message);
                        // 即使数据库初始化失败，也尝试设置基础事件监听
                        setupEventListeners();
                    });
                
            } catch (error) {
                const message = `应用初始化过程中发生错误: ${error.message}`;
                console.error(message, error);
                showError(message);
            }
        });
        
        // 初始化IndexedDB
        function initDB() {
            return new Promise((resolve, reject) => {
                try {
                    // 检查浏览器是否支持IndexedDB
                    if (!window.indexedDB) {
                        const error = new Error('您的浏览器不支持IndexedDB，无法使用应用功能');
                        return reject(error);
                    }
                    
                    // 打开数据库
                    const request = indexedDB.open(DB_CONFIG.name, DB_CONFIG.version);
                    
                    // 数据库升级或首次创建
                    request.onupgradeneeded = function(event) {
                        try {
                            const db = event.target.result;
                            
                            // 如果存储库不存在则创建
                            if (!db.objectStoreNames.contains(DB_CONFIG.storeName)) {
                                const store = db.createObjectStore(DB_CONFIG.storeName, { 
                                    keyPath: 'id',
                                    autoIncrement: false 
                                });
                                
                                // 创建索引，便于查询
                                store.createIndex('type', 'type', { unique: false });
                                store.createIndex('date', 'date', { unique: false });
                            }
                        } catch (error) {
                            reject(error);
                        }
                    };
                    
                    // 成功打开数据库
                    request.onsuccess = function(event) {
                        try {
                            db = event.target.result;
                            
                            // 监听数据库版本变化
                            db.onversionchange = function(event) {
                                db.close();
                            };
                            
                            resolve(db);
                        } catch (error) {
                            reject(error);
                        }
                    };
                    
                    // 打开数据库失败
                    request.onerror = function(event) {
                        reject(event.target.error);
                    };
                    
                    // 阻止默认冒泡
                    request.addEventListener('error', function(event) {
                        event.stopPropagation();
                    });
                    
                } catch (error) {
                    reject(error);
                }
            });
        }
        
        // 向数据库添加记录
        function addRecordToDB(record) {
            return new Promise((resolve, reject) => {
                try {
                    if (!db) {
                        const error = new Error('数据库未初始化');
                        return reject(error);
                    }
                    
                    // 开始事务
                    const transaction = db.transaction(DB_CONFIG.storeName, 'readwrite');
                    const store = transaction.objectStore(DB_CONFIG.storeName);
                    
                    // 添加记录
                    const request = store.add(record);
                    
                    request.onsuccess = function() {
                        resolve(true);
                    };
                    
                    request.onerror = function(event) {
                        reject(event.target.error);
                    };
                    
                    transaction.oncomplete = function() {
                    };
                    
                    transaction.onerror = function(event) {
                        reject(event.target.error);
                    };
                    
                } catch (error) {
                    reject(error);
                }
            });
        }
        
        // 从数据库获取所有记录
        function getAllRecordsFromDB() {
            return new Promise((resolve, reject) => {
                try {
                    if (!db) {
                        const error = new Error('数据库未初始化');
                        return reject(error);
                    }
                    
                    const transaction = db.transaction(DB_CONFIG.storeName, 'readonly');
                    const store = transaction.objectStore(DB_CONFIG.storeName);
                    const request = store.getAll();
                    
                    request.onsuccess = function() {
                        resolve(request.result);
                    };
                    
                    request.onerror = function(event) {
                        reject(event.target.error);
                    };
                    
                } catch (error) {
                    reject(error);
                }
            });
        }
        
        // 从数据库删除记录
        function deleteRecordFromDB(id) {
            return new Promise((resolve, reject) => {
                try {
                    if (!db) {
                        const error = new Error('数据库未初始化');
                        return reject(error);
                    }
                    
                    const transaction = db.transaction(DB_CONFIG.storeName, 'readwrite');
                    const store = transaction.objectStore(DB_CONFIG.storeName);
                    const request = store.delete(id);
                    
                    request.onsuccess = function() {
                        resolve(true);
                    };
                    
                    request.onerror = function(event) {
                        reject(event.target.error);
                    };
                    
                } catch (error) {
                    reject(error);
                }
            });
        }
        
        // 清空数据库所有记录
        function clearAllRecordsFromDB() {
            return new Promise((resolve, reject) => {
                try {
                    if (!db) {
                        const error = new Error('数据库未初始化');
                        return reject(error);
                    }
                    
                    const transaction = db.transaction(DB_CONFIG.storeName, 'readwrite');
                    const store = transaction.objectStore(DB_CONFIG.storeName);
                    const request = store.clear();
                    
                    request.onsuccess = function() {
                        resolve(true);
                    };
                    
                    request.onerror = function(event) {
                        reject(event.target.error);
                    };
                    
                } catch (error) {
                    reject(error);
                }
            });
        }
        
        // 导出数据
        function exportData() {
            getAllRecordsFromDB()
                .then(records => {
                    const dataStr = JSON.stringify(records, null, 2);
                    const dataBlob = new Blob([dataStr], { type: 'application/json' });
                    const url = URL.createObjectURL(dataBlob);
                    
                    const exportFileName = `car-expenses-${new Date().toISOString().split('T')[0]}.json`;
                    
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = exportFileName;
                    document.body.appendChild(a);
                    a.click();
                    
                    setTimeout(() => {
                        document.body.removeChild(a);
                        URL.revokeObjectURL(url);
                    }, 100);
                    
                    showToast('数据导出成功');
                })
                .catch(error => {
                    showError(`导出失败: ${error.message}`);
                });
        }
        
        // 导入数据
        function importData(file) {
            const reader = new FileReader();
            
            reader.onload = function(event) {
                try {
                    const records = JSON.parse(event.target.result);
                    
                    if (!Array.isArray(records)) {
                        throw new Error('导入的数据格式不正确，应为数组');
                    }
                    
                    // 开启事务批量导入
                    const transaction = db.transaction(DB_CONFIG.storeName, 'readwrite');
                    const store = transaction.objectStore(DB_CONFIG.storeName);
                    
                    let importedCount = 0;
                    let errorCount = 0;
                    
                    records.forEach(record => {
                        // 确保记录有必要的字段
                        if (record.id && record.type && record.date) {
                            // 过路费记录不需要里程
                            if (record.type !== 'toll' || record.odometer !== undefined) {
                                // 处理旧格式的过路费记录
                                if (record.type === 'toll' && record.location && !record.startLocation) {
                                    // 将旧的location字段转换为startLocation
                                    record.startLocation = record.location;
                                    record.endLocation = '';
                                    delete record.location;
                                }
                                
                                const request = store.put(record); // 使用put而不是add，允许覆盖现有记录
                                
                                request.onsuccess = function() {
                                    importedCount++;
                                };
                                
                                request.onerror = function() {
                                    errorCount++;
                                };
                            } else {
                                errorCount++;
                            }
                        } else {
                            errorCount++;
                        }
                    });
                    
                    transaction.oncomplete = function() {
                        showToast(`数据导入成功: ${importedCount} 条记录`);
                        loadRecords()
                            .then(() => updateQuickStats())
                            .then(() => calculateStats());
                    };
                    
                    transaction.onerror = function() {
                        showError(`导入失败: ${transaction.error}`);
                    };
                    
                } catch (error) {
                    showError(`导入失败: ${error.message}`);
                }
            };
            
            reader.readAsText(file);
        }
        
        // 设置所有事件监听器
        function setupEventListeners() {
            try {
                // 定义需要绑定事件的元素及其处理函数
                const eventListeners = [
                    // 首页卡片点击事件
                    { id: 'fuelCard', event: 'click', handler: () => switchToEntryForm('fuel') },
                    { id: 'tollCard', event: 'click', handler: () => switchToEntryForm('toll') },
                    { id: 'maintenanceCard', event: 'click', handler: () => switchToEntryForm('maintenance') },
                    
                    // 返回按钮事件
                    { id: 'backToHome', event: 'click', handler: () => switchSection('landing') },
                    { id: 'backFromHistory', event: 'click', handler: () => switchSection('landing') },
                    { id: 'backFromSettings', event: 'click', handler: () => switchSection('landing') },
                    { id: 'backFromStats', event: 'click', handler: () => switchSection('landing') },
                    
                    // 底部菜单按钮事件
                    { id: 'landingBtn', event: 'click', handler: () => switchSection('landing') },
                    { id: 'historyBtn', event: 'click', handler: () => {
                        switchSection('history');
                        // 切换到历史页面时刷新记录列表
                        loadRecords(getActiveFilter()).catch(err => {
                            showError('加载历史记录失败: ' + err.message);
                        });
                    }},
                    
                    // 统计和设置按钮事件
                    { id: 'statsBtn', event: 'click', handler: function() {
                        switchSection('stats');
                        calculateStats().catch(error => {
                            showToast(`统计计算失败: ${error.message}`, 'error');
                        });
                    }},
                    { id: 'settingsBtnHeader', event: 'click', handler: () => switchSection('settings') },
                    
                    // 设置页面按钮事件
                    { id: 'exportDataBtn', event: 'click', handler: exportData },
                    
                    // 导入数据相关
                    { id: 'importDataBtn', event: 'click', handler: () => {
                        const importFileInput = document.getElementById('importFileInput');
                        if (importFileInput) importFileInput.click();
                    }},
                    
                    { id: 'importFileInput', event: 'change', handler: function(event) {
                        if (event.target.files && event.target.files[0]) {
                            const file = event.target.files[0];
                            importData(file);
                            // 重置输入，允许重复选择同一文件
                            event.target.value = '';
                        }
                    }},
                    
                    { id: 'clearAllDataBtn', event: 'click', handler: function() {
                        if (confirm('确定要删除所有记录吗？此操作不可恢复！')) {
                            clearAllRecordsFromDB()
                                .then(() => {
                                    loadRecords()
                                        .then(() => updateQuickStats())
                                        .then(() => calculateStats())
                                        .then(() => {
                                            showToast('所有记录已清空');
                                        });
                                })
                                .catch(error => {
                                    showToast(`清空数据失败: ${error.message}`, 'error');
                                });
                        }
                    }},
                    
                    // 关于按钮
                    { id: 'aboutBtn', event: 'click', handler: function() {
                        const aboutModal = document.getElementById('aboutModal');
                        const modalAboutContent = document.getElementById('modalAboutContent');
                        if (aboutModal && modalAboutContent) {
                            showModal(aboutModal, modalAboutContent);
                        }
                    }},
                    
                    // 搜索记录
                    { id: 'searchRecords', event: 'input', handler: function() {
                        const searchTerm = this.value.toLowerCase();
                        filterRecordsBySearch(searchTerm);
                    }},
                    
                    // 计算相关事件
                    { id: 'fuelAmount', event: 'input', handler: updateFuelCalculations },
                    { id: 'fuelTotal', event: 'input', handler: updateFuelCalculations },
                    { id: 'odometer', event: 'input', handler: updateFuelCalculations },
                    
                    // 表单提交事件
                    { id: 'expenseForm', event: 'submit', handler: handleFormSubmit }
                ];
                
                // 绑定过滤按钮事件
                const filterTypes = ['All', 'Fuel', 'Toll', 'Maintenance'];
                filterTypes.forEach(type => {
                    const filterId = `filter${type}`;
                    eventListeners.push({
                        id: filterId,
                        event: 'click',
                        handler: function() {
                            const filter = this.id.replace('filter', '').toLowerCase();
                            setActiveFilter(filter);
                            filterRecords(filter);
                        }
                    });
                });
                
                // 绑定关闭弹窗按钮事件
                const closeButtons = document.querySelectorAll('.close-modal');
                closeButtons.forEach(btn => {
                    btn.addEventListener('click', function() {
                        const modal = this.closest('.fixed');
                        closeModal(modal);
                    });
                });
                
                // 点击弹窗外部关闭
                const modals = document.querySelectorAll('#aboutModal');
                modals.forEach(modal => {
                    modal.addEventListener('click', function(e) {
                        if (e.target === this) {
                            closeModal(this);
                        }
                    });
                });
                
                // 绑定所有事件，检查元素是否存在
                eventListeners.forEach(item => {
                    const element = document.getElementById(item.id);
                    if (element) {
                        // 先移除可能存在的事件监听器，避免重复绑定
                        element.removeEventListener(item.event, item.handler);
                        element.addEventListener(item.event, item.handler);
                    } else {
                        console.warn(`未找到元素: ${item.id}，无法绑定事件`);
                    }
                });
                
                // 显式绑定保存按钮事件（作为表单提交的备份）
                const saveButton = document.getElementById('saveButton');
                if (saveButton) {
                    saveButton.addEventListener('click', function(e) {
                        // 触发表单提交
                        const form = document.getElementById('expenseForm');
                        if (form) {
                            const submitEvent = new Event('submit', { cancelable: true });
                            form.dispatchEvent(submitEvent);
                        } else {
                            showError('无法找到表单，保存失败');
                        }
                    });
                } else {
                    console.warn('未找到保存按钮');
                }
                
            } catch (error) {
                showError('初始化事件监听失败: ' + error.message);
            }
        }
        
        // 切换到记录表单并设置类型
        function switchToEntryForm(type) {
            try {
                // 更新表单类型
                const expenseTypeEl = document.getElementById('expenseType');
                if (expenseTypeEl) {
                    expenseTypeEl.value = type;
                } else {
                    showError('未找到表单类型元素');
                    return;
                }
                
                // 显示/隐藏对应字段
                const fuelFields = document.getElementById('fuelFields');
                const tollFields = document.getElementById('tollFields');
                const maintenanceFields = document.getElementById('maintenanceFields');
                
                if (fuelFields) fuelFields.classList.add('hidden');
                if (tollFields) tollFields.classList.add('hidden');
                if (maintenanceFields) maintenanceFields.classList.add('hidden');
                
                // 控制里程字段的显示 - 过路费不显示里程
                const odometerField = document.getElementById('odometerField');
                if (odometerField) {
                    if (type === 'toll') {
                        odometerField.classList.add('hidden');
                    } else {
                        odometerField.classList.remove('hidden');
                    }
                }
                
                // 显示对应字段
                if (type === 'fuel' && fuelFields) {
                    fuelFields.classList.remove('hidden');
                    calculateEfficiency();
                    const entryTitle = document.getElementById('entryTitle');
                    if (entryTitle) entryTitle.textContent = '添加加油记录';
                } else if (type === 'toll' && tollFields) {
                    tollFields.classList.remove('hidden');
                    const entryTitle = document.getElementById('entryTitle');
                    if (entryTitle) entryTitle.textContent = '添加过路费记录';
                } else if (type === 'maintenance' && maintenanceFields) {
                    maintenanceFields.classList.remove('hidden');
                    const entryTitle = document.getElementById('entryTitle');
                    if (entryTitle) entryTitle.textContent = '添加保养记录';
                }
                
                // 切换到表单页面
                switchSection('entry');
            } catch (error) {
                showError('切换到表单失败: ' + error.message);
            }
        }
        
        // 切换页面 section
        function switchSection(sectionName) {
            try {
                // 隐藏所有section
                document.querySelectorAll('.section').forEach(section => {
                    section.classList.remove('active');
                });
                
                // 显示目标section
                const targetSection = document.getElementById(`${sectionName}Section`);
                if (targetSection) {
                    targetSection.classList.add('active');
                    
                    // 更新底部菜单高亮状态
                    document.querySelectorAll('footer button').forEach(btn => {
                        btn.classList.remove('menu-item-active');
                    });
                    
                    // 根据当前section设置对应的底部菜单高亮
                    if (sectionName === 'landing') {
                        const activeBtn = document.getElementById('landingBtn');
                        if (activeBtn) activeBtn.classList.add('menu-item-active');
                    } else if (sectionName === 'history') {
                        const activeBtn = document.getElementById('historyBtn');
                        if (activeBtn) activeBtn.classList.add('menu-item-active');
                    } else if (sectionName === 'stats') {
                        const activeBtn = document.getElementById('statsBtn');
                        if (activeBtn) activeBtn.classList.add('menu-item-active');
                    } else if (sectionName === 'settings') {
                        const activeBtn = document.getElementById('settingsBtnHeader');
                        if (activeBtn) activeBtn.classList.add('menu-item-active');
                    }
                } else {
                    showError('页面切换失败');
                }
            } catch (error) {
                showError('页面切换失败: ' + error.message);
            }
        }
        
        // 处理表单提交
        async function handleFormSubmit(e) {
            try {
                e.preventDefault();
                e.stopPropagation();
                
                // 验证表单数据
                if (!validateFormData()) {
                    return;
                }
                
                // 收集表单数据
                const formData = collectFormData();
                
                // 保存记录到数据库
                const saveSuccess = await addRecordToDB(formData);
                
                if (saveSuccess) {
                    // 重置表单
                    const expenseType = document.getElementById('expenseType').value;
                    const expenseForm = document.getElementById('expenseForm');
                    if (expenseForm) {
                        expenseForm.reset();
                        const dateInput = document.getElementById('date');
                        if (dateInput) {
                            dateInput.value = new Date().toISOString().split('T')[0];
                        }
                    }
                    
                    await populateLastOdometer();
                    
                    // 重新加载记录列表和首页数据
                    await loadRecords(getActiveFilter());
                    await updateQuickStats();
                    await calculateStats();
                    
                    showToast('记录保存成功');
                    
                    // 返回首页
                    switchSection('landing');
                }
                
            } catch (error) {
                showError(`保存失败: ${error.message}`);
            }
        }
        
        // 验证表单数据
        function validateFormData() {
            try {
                let isValid = true;
                const typeEl = document.getElementById('expenseType');
                if (!typeEl) {
                    showError('未找到表单类型元素');
                    return false;
                }
                
                const type = typeEl.value;
                const odometer = document.getElementById('odometer');
                
                // 清除之前的错误状态
                document.querySelectorAll('input, select').forEach(el => {
                    el.classList.remove('error-border');
                });
                
                // 验证里程 - 仅在加油和保养时需要
                if (type !== 'toll' && odometer && (!odometer.value || isNaN(odometer.value) || parseFloat(odometer.value) <= 0)) {
                    odometer.classList.add('error-border');
                    isValid = false;
                }
                
                // 根据类型验证特有字段
                if (type === 'fuel') {
                    const fuelAmount = document.getElementById('fuelAmount');
                    const fuelTotal = document.getElementById('fuelTotal');
                    
                    if (fuelAmount && (!fuelAmount.value || isNaN(fuelAmount.value) || parseFloat(fuelAmount.value) <= 0)) {
                        fuelAmount.classList.add('error-border');
                        isValid = false;
                    }
                    
                    if (fuelTotal && (!fuelTotal.value || isNaN(fuelTotal.value) || parseFloat(fuelTotal.value) <= 0)) {
                        fuelTotal.classList.add('error-border');
                        isValid = false;
                    }
                } else if (type === 'toll') {
                    const tollAmount = document.getElementById('tollAmount');
                    const tollStartLocation = document.getElementById('tollStartLocation');
                    const tollEndLocation = document.getElementById('tollEndLocation');
                    
                    if (tollAmount && (!tollAmount.value || isNaN(tollAmount.value) || parseFloat(tollAmount.value) <= 0)) {
                        tollAmount.classList.add('error-border');
                        isValid = false;
                    }
                    
                    if (tollStartLocation && !tollStartLocation.value.trim()) {
                        tollStartLocation.classList.add('error-border');
                        isValid = false;
                    }
                    
                    if (tollEndLocation && !tollEndLocation.value.trim()) {
                        tollEndLocation.classList.add('error-border');
                        isValid = false;
                    }
                } else if (type === 'maintenance') {
                    const maintenanceAmount = document.getElementById('maintenanceAmount');
                    if (maintenanceAmount && (!maintenanceAmount.value || isNaN(maintenanceAmount.value) || parseFloat(maintenanceAmount.value) <= 0)) {
                        maintenanceAmount.classList.add('error-border');
                        isValid = false;
                    }
                }
                
                return isValid;
                
            } catch (error) {
                showError('验证表单时出错: ' + error.message);
                return false;
            }
        }
        
        // 收集表单数据
        function collectFormData() {
            try {
                const typeEl = document.getElementById('expenseType');
                const dateEl = document.getElementById('date');
                const notesEl = document.getElementById('notes');
                
                if (!typeEl || !dateEl) {
                    throw new Error('表单关键元素缺失');
                }
                
                const type = typeEl.value;
                const date = dateEl.value;
                const notes = notesEl ? notesEl.value : '';
                
                const record = {
                    id: Date.now(), // 使用时间戳作为唯一ID，确保新记录ID更大
                    type: type,
                    date: date,
                    notes: notes,
                    timestamp: Date.now() // 添加时间戳用于精确排序
                };
                
                // 只有加油和保养记录需要里程
                if (type !== 'toll') {
                    const odometerEl = document.getElementById('odometer');
                    if (odometerEl && odometerEl.value) {
                        record.odometer = parseFloat(odometerEl.value);
                    } else {
                        throw new Error('里程信息缺失');
                    }
                }
                
                // 根据类型添加特有字段
                if (type === 'fuel') {
                    const fuelTypeEl = document.getElementById('fuelType');
                    const fuelAmountEl = document.getElementById('fuelAmount');
                    const fuelTotalEl = document.getElementById('fuelTotal');
                    const fuelPriceEl = document.getElementById('fuelPrice');
                    
                    if (!fuelTypeEl || !fuelAmountEl || !fuelTotalEl || !fuelPriceEl) {
                        throw new Error('加油记录字段缺失');
                    }
                    
                    record.fuelType = fuelTypeEl.value;
                    record.amount = parseFloat(fuelAmountEl.value);
                    record.total = parseFloat(fuelTotalEl.value);
                    record.price = parseFloat(fuelPriceEl.value);
                } else if (type === 'toll') {
                    const tollAmountEl = document.getElementById('tollAmount');
                    const tollPaymentMethodEl = document.getElementById('tollPaymentMethod');
                    const tollStartLocationEl = document.getElementById('tollStartLocation');
                    const tollEndLocationEl = document.getElementById('tollEndLocation');
                    
                    if (!tollAmountEl || !tollPaymentMethodEl || !tollStartLocationEl || !tollEndLocationEl) {
                        throw new Error('过路费记录字段缺失');
                    }
                    
                    record.total = parseFloat(tollAmountEl.value);
                    record.paymentMethod = tollPaymentMethodEl.value;
                    record.startLocation = tollStartLocationEl.value;
                    record.endLocation = tollEndLocationEl.value;
                } else if (type === 'maintenance') {
                    const maintenanceAmountEl = document.getElementById('maintenanceAmount');
                    const maintenanceTypeEl = document.getElementById('maintenanceType');
                    
                    if (!maintenanceAmountEl) {
                        throw new Error('保养记录字段缺失');
                    }
                    
                    record.total = parseFloat(maintenanceAmountEl.value);
                    record.maintenanceType = maintenanceTypeEl ? maintenanceTypeEl.value : '';
                }
                
                return record;
                
            } catch (error) {
                showError('收集表单数据时出错: ' + error.message);
                throw error;
            }
        }
        
        // 从数据库加载记录并显示（确保最新的在最前面）
        async function loadRecords(filter = 'all') {
            try {
                const records = await getAllRecordsFromDB();
                
                // 按时间戳降序排序，确保最新的记录在最前面
                // 对于没有时间戳的旧记录，使用ID作为备用排序依据
                records.sort((a, b) => {
                    const timeA = a.timestamp || a.id;
                    const timeB = b.timestamp || b.id;
                    return timeB - timeA; // 降序排列，最新的在前面
                });
                
                // 应用过滤
                const filteredRecords = filter === 'all' 
                    ? records 
                    : records.filter(r => r.type === filter);
                
                const recordsList = document.getElementById('recordsList');
                if (!recordsList) {
                    throw new Error('未找到记录列表容器');
                }
                
                if (filteredRecords.length === 0) {
                    recordsList.innerHTML = `
                        <div class="text-center text-gray-500 py-10">
                            <i class="fas fa-file-alt text-4xl mb-3 opacity-30"></i>
                            <p>暂无记录，添加您的第一条记录吧</p>
                        </div>
                    `;
                    return;
                }
                
                recordsList.innerHTML = '';
                
                filteredRecords.forEach(record => {
                    // 如果是加油记录，计算油耗
                    if (record.type === 'fuel') {
                        calculateAndAddEfficiency(record, records);
                    }
                    
                    const recordEl = createRecordElement(record);
                    recordsList.appendChild(recordEl);
                });
                
                // 添加删除事件监听
                document.querySelectorAll('.delete-record').forEach(btn => {
                    btn.addEventListener('click', async function() {
                        const id = parseInt(this.getAttribute('data-id'));
                        await deleteRecord(id);
                    });
                });
                
            } catch (error) {
                showError(`加载记录失败: ${error.message}`);
            }
        }
        
        // 更新首页快速统计
        async function updateQuickStats() {
            try {
                const records = await getAllRecordsFromDB();
                let monthTotal = 0;
                let fuelTotal = 0;
                
                const today = new Date();
                const currentMonth = today.getMonth();
                const currentYear = today.getFullYear();
                
                records.forEach(record => {
                    // 统计加油总费用
                    if (record.type === 'fuel') {
                        fuelTotal += record.total;
                    }
                    
                    // 统计本月总支出
                    const recordDate = new Date(record.date);
                    if (recordDate.getMonth() === currentMonth && recordDate.getFullYear() === currentYear) {
                        monthTotal += record.total;
                    }
                });
                
                // 更新显示
                const quickMonthTotal = document.getElementById('quickMonthTotal');
                const quickFuelTotal = document.getElementById('quickFuelTotal');
                const quickRecordCount = document.getElementById('quickRecordCount');
                
                if (quickMonthTotal) quickMonthTotal.textContent = `¥${monthTotal.toFixed(2)}`;
                if (quickFuelTotal) quickFuelTotal.textContent = `¥${fuelTotal.toFixed(2)}`;
                if (quickRecordCount) quickRecordCount.textContent = records.length;
                
            } catch (error) {
                console.error(`更新快速统计失败: ${error.message}`);
            }
        }
        
        // 按搜索词过滤记录
        async function filterRecordsBySearch(searchTerm) {
            try {
                if (!searchTerm.trim()) {
                    // 如果搜索词为空，使用当前激活的过滤器
                    loadRecords(getActiveFilter());
                    return;
                }
                
                const records = await getAllRecordsFromDB();
                
                // 按时间戳降序排序，确保最新的在前面
                records.sort((a, b) => {
                    const timeA = a.timestamp || a.id;
                    const timeB = b.timestamp || b.id;
                    return timeB - timeA;
                });
                
                // 应用搜索过滤
                let filteredRecords = records.filter(record => {
                    // 检查不同类型记录的相关字段
                    if (record.type === 'fuel') {
                        return record.fuelType.toLowerCase().includes(searchTerm) ||
                               record.notes.toLowerCase().includes(searchTerm) ||
                               record.date.includes(searchTerm);
                    } else if (record.type === 'toll') {
                        return (record.startLocation && record.startLocation.toLowerCase().includes(searchTerm)) ||
                               (record.endLocation && record.endLocation.toLowerCase().includes(searchTerm)) ||
                               (record.paymentMethod && record.paymentMethod.toLowerCase().includes(searchTerm)) ||
                               record.notes.toLowerCase().includes(searchTerm) ||
                               record.date.includes(searchTerm);
                    } else if (record.type === 'maintenance') {
                        return (record.maintenanceType && record.maintenanceType.toLowerCase().includes(searchTerm)) ||
                               record.notes.toLowerCase().includes(searchTerm) ||
                               record.date.includes(searchTerm);
                    }
                    return false;
                });
                
                // 同时应用当前的类型过滤器
                const activeFilter = getActiveFilter();
                if (activeFilter !== 'all') {
                    filteredRecords = filteredRecords.filter(r => r.type === activeFilter);
                }
                
                const recordsList = document.getElementById('recordsList');
                if (!recordsList) {
                    throw new Error('未找到记录列表容器');
                }
                
                if (filteredRecords.length === 0) {
                    recordsList.innerHTML = `
                        <div class="text-center text-gray-500 py-10">
                            <i class="fas fa-search text-4xl mb-3 opacity-30"></i>
                            <p>未找到匹配的记录</p>
                        </div>
                    `;
                    return;
                }
                
                recordsList.innerHTML = '';
                
                filteredRecords.forEach(record => {
                    // 如果是加油记录，计算油耗
                    if (record.type === 'fuel') {
                        calculateAndAddEfficiency(record, records);
                    }
                    
                    const recordEl = createRecordElement(record);
                    recordsList.appendChild(recordEl);
                });
                
                // 添加删除事件监听
                document.querySelectorAll('.delete-record').forEach(btn => {
                    btn.addEventListener('click', async function() {
                        const id = parseInt(this.getAttribute('data-id'));
                        await deleteRecord(id);
                    });
                });
                
            } catch (error) {
                showError(`搜索记录失败: ${error.message}`);
            }
        }
        
        // 计算并添加油耗信息 - 改进版：忽略首次加油记录的油耗计算
        function calculateAndAddEfficiency(currentRecord, allRecords) {
            try {
                // 1. 筛选出所有加油记录并按日期排序（旧到新）- 用于计算油耗
                const fuelRecords = allRecords
                    .filter(r => r.type === 'fuel')
                    .sort((a, b) => new Date(a.date) - new Date(b.date));
                
                // 2. 如果只有一条加油记录，不计算油耗
                if (fuelRecords.length <= 1) {
                    currentRecord.efficiency = null;
                    currentRecord.efficiencyNote = '需至少两次加油记录';
                    return;
                }
                
                // 3. 找到当前记录在排序后的位置
                const currentIndex = fuelRecords.findIndex(r => r.id === currentRecord.id);
                
                // 4. 只有当前记录不是第一条加油记录时才能计算油耗
                if (currentIndex > 0) {
                    const previousRecord = fuelRecords[currentIndex - 1];
                    
                    // 5. 验证数据有效性
                    if (previousRecord.odometer === undefined || currentRecord.odometer === undefined) {
                        console.warn('无法计算油耗：里程数据缺失');
                        currentRecord.efficiency = null;
                        currentRecord.efficiencyNote = '里程数据缺失';
                        return;
                    }
                    
                    // 6. 检查里程是否合理（当前里程应大于上次里程）
                    if (currentRecord.odometer <= previousRecord.odometer) {
                        console.warn('无法计算油耗：当前里程小于等于上次里程');
                        currentRecord.efficiency = null;
                        currentRecord.efficiencyNote = '里程数据不合理';
                        return;
                    }
                    
                    // 7. 检查加油量是否有效
                    if (currentRecord.amount <= 0) {
                        console.warn('无法计算油耗：加油量必须大于0');
                        currentRecord.efficiency = null;
                        currentRecord.efficiencyNote = '加油量数据无效';
                        return;
                    }
                    
                    // 8. 计算行驶里程
                    const distance = currentRecord.odometer - previousRecord.odometer;
                    
                    // 9. 计算油耗（升/百公里）= (加油量 ÷ 行驶里程) × 100
                    currentRecord.efficiency = (currentRecord.amount / distance) * 100;
                    currentRecord.distance = distance; // 存储行驶里程用于显示
                } else {
                    // 第一条加油记录无法计算油耗
                    currentRecord.efficiency = null;
                    currentRecord.efficiencyNote = '第一条记录无油耗数据';
                }
            } catch (error) {
                console.error(`计算油耗时出错: ${error.message}`);
                currentRecord.efficiency = null;
                currentRecord.efficiencyNote = '计算错误';
            }
        }
        
        // 创建记录元素
        function createRecordElement(record) {
            try {
                const recordEl = document.createElement('div');
                recordEl.className = 'bg-white rounded-lg shadow-sm p-3 transition-custom hover:shadow-md record-item';
                recordEl.setAttribute('data-type', record.type);
                
                let typeIcon, typeText, typeClass, detailsHtml;
                
                // 根据类型设置不同样式和内容
                if (record.type === 'fuel') {
                    typeIcon = 'fa-gas-pump';
                    typeText = '加油';
                    typeClass = 'bg-yellow-100 text-yellow-600';
                    
                    // 转换油品类型显示文本
                    let fuelTypeText = '';
                    switch(record.fuelType) {
                        case '92': fuelTypeText = '92号汽油'; break;
                        case '95': fuelTypeText = '95号汽油'; break;
                        case '98': fuelTypeText = '98号汽油'; break;
                        case 'diesel': fuelTypeText = '柴油'; break;
                        default: fuelTypeText = '其他';
                    }
                    
                    // 添加油耗信息（如果有）
                    let efficiencyHtml = '';
                    if (record.efficiency !== null && !isNaN(record.efficiency)) {
                        efficiencyHtml = `<span class="ml-2 text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded-full">
                            油耗: ${record.efficiency.toFixed(2)}L/100km (行驶${record.distance.toFixed(1)}km)
                        </span>`;
                    } else if (record.efficiencyNote) {
                        efficiencyHtml = `<span class="ml-2 text-xs bg-gray-100 text-gray-700 px-2 py-0.5 rounded-full">
                            ${record.efficiencyNote}
                        </span>`;
                    }
                    
                    detailsHtml = `
                        <div class="text-xs text-gray-500 mt-1">
                            <p>${fuelTypeText} · ${record.amount}升 · ${record.price}元/升 · 里程: ${record.odometer}km ${efficiencyHtml}</p>
                        </div>
                    `;
                } else if (record.type === 'toll') {
                    typeIcon = 'fa-road';
                    typeText = '过路费';
                    typeClass = 'bg-blue-100 text-blue-600';
                    
                    // 转换支付方式显示文本
                    let paymentMethodText = '';
                    switch(record.paymentMethod) {
                        case 'etc': paymentMethodText = 'ETC'; break;
                        case 'wechat': paymentMethodText = '微信支付'; break;
                        case 'alipay': paymentMethodText = '支付宝'; break;
                        case 'cash': paymentMethodText = '现金'; break;
                        default: paymentMethodText = '其他';
                    }
                    
                    detailsHtml = `
                        <div class="text-xs text-gray-500 mt-1">
                            <p><i class="fas fa-map-marker-alt mr-1 text-gray-400"></i>${record.startLocation} → ${record.endLocation}</p>
                            <p><i class="fas fa-credit-card mr-1 text-gray-400"></i>支付方式: ${paymentMethodText}</p>
                        </div>
                    `;
                } else if (record.type === 'maintenance') {
                    typeIcon = 'fa-wrench';
                    typeText = '保养';
                    typeClass = 'bg-green-100 text-green-600';
                    
                    detailsHtml = `
                        <div class="text-xs text-gray-500 mt-1">
                            <p>里程: ${record.odometer}km</p>
                            ${record.maintenanceType ? `<p>${record.maintenanceType}</p>` : ''}
                        </div>
                    `;
                }
                
                // 格式化日期
                const date = new Date(record.date);
                const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
                
                recordEl.innerHTML = `
                    <div class="flex justify-between items-start">
                        <div>
                            <div class="flex items-center flex-wrap">
                                <span class="px-2 py-1 rounded-full text-xs font-medium ${typeClass}">
                                    <i class="fas ${typeIcon} mr-1"></i>${typeText}
                                </span>
                                <span class="ml-2 text-xs text-gray-500">${formattedDate}</span>
                            </div>
                            ${detailsHtml}
                            ${record.notes ? `
                                <div class="text-xs text-gray-600 mt-2 italic">
                                    <i class="fas fa-comment-alt mr-1 text-gray-400"></i>${record.notes}
                                </div>
                            ` : ''}
                        </div>
                        <div class="text-right">
                            <p class="text-base font-bold text-primary">${record.total.toFixed(2)}元</p>
                            <button class="delete-record text-gray-400 hover:text-red-500 mt-1 transition-custom" data-id="${record.id}">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                        </div>
                    </div>
                `;
                
                return recordEl;
            } catch (error) {
                // 返回一个错误提示元素
                const errorEl = document.createElement('div');
                errorEl.className = 'bg-red-50 p-3 rounded-lg text-red-500';
                errorEl.textContent = '加载记录时出错';
                return errorEl;
            }
        }
        
        // 删除记录
        async function deleteRecord(id) {
            try {
                if (confirm('确定要删除这条记录吗？')) {
                    await deleteRecordFromDB(id);
                    await loadRecords(getActiveFilter());
                    await updateQuickStats();
                    await calculateStats();
                    showToast('记录已删除');
                }
            } catch (error) {
                showError(`删除失败: ${error.message}`);
            }
        }
        
        // 更新燃油计算（单价和油耗）
        async function updateFuelCalculations() {
            try {
                const fuelAmount = document.getElementById('fuelAmount');
                const fuelTotal = document.getElementById('fuelTotal');
                const fuelPrice = document.getElementById('fuelPrice');
                
                if (!fuelAmount || !fuelTotal || !fuelPrice) {
                    console.warn('燃油计算相关元素缺失');
                    return;
                }
                
                // 计算单价
                if (fuelAmount.value && fuelTotal.value && parseFloat(fuelAmount.value) > 0) {
                    const price = parseFloat(fuelTotal.value) / parseFloat(fuelAmount.value);
                    fuelPrice.value = price.toFixed(2);
                } else {
                    fuelPrice.value = '';
                }
                
                // 计算油耗
                await calculateEfficiency();
                
            } catch (error) {
                console.error(`更新燃油计算时出错: ${error.message}`);
            }
        }
        
        // 计算油耗 - 改进版：忽略首次加油记录的油耗计算
        async function calculateEfficiency() {
            try {
                const fuelAmount = document.getElementById('fuelAmount');
                const odometer = document.getElementById('odometer');
                const fuelEfficiency = document.getElementById('fuelEfficiency');
                const efficiencyNote = document.getElementById('efficiencyNote');
                
                if (!fuelAmount || !odometer || !fuelEfficiency || !efficiencyNote) {
                    console.warn('油耗计算相关元素缺失');
                    return;
                }
                
                // 获取所有加油记录并按日期排序（旧到新）
                const records = await getAllRecordsFromDB();
                const fuelRecords = records
                    .filter(r => r.type === 'fuel')
                    .sort((a, b) => new Date(a.date) - new Date(b.date));
                
                // 至少需要一条之前的记录才能计算油耗
                if (fuelRecords.length === 0) {
                    fuelEfficiency.value = '';
                    efficiencyNote.textContent = '* 这是第一条加油记录，无法计算油耗';
                    return;
                }
                
                // 如果只有一条加油记录，不计算油耗
                if (fuelRecords.length === 1) {
                    fuelEfficiency.value = '';
                    efficiencyNote.textContent = '* 至少需要两次加油记录才能计算油耗';
                    return;
                }
                
                // 获取最新的一条加油记录作为上次记录
                const lastRecord = fuelRecords[fuelRecords.length - 1];
                
                // 验证当前输入的有效性
                if (!fuelAmount.value || !odometer.value) {
                    fuelEfficiency.value = '';
                    efficiencyNote.textContent = '* 请输入加油量和当前里程';
                    return;
                }
                
                const currentOdometer = parseFloat(odometer.value);
                const lastOdometer = parseFloat(lastRecord.odometer);
                const fuel = parseFloat(fuelAmount.value);
                
                // 验证数据合理性
                if (currentOdometer <= lastOdometer) {
                    fuelEfficiency.value = '';
                    efficiencyNote.textContent = '* 错误: 当前里程必须大于上次里程';
                    odometer.classList.add('error-border');
                    return;
                } else {
                    odometer.classList.remove('error-border');
                }
                
                if (fuel <= 0) {
                    fuelEfficiency.value = '';
                    efficiencyNote.textContent = '* 错误: 加油量必须大于0';
                    fuelAmount.classList.add('error-border');
                    return;
                } else {
                    fuelAmount.classList.remove('error-border');
                }
                
                // 计算行驶里程
                const distance = currentOdometer - lastOdometer;
                
                // 计算油耗（升/百公里）= (加油量 ÷ 行驶里程) × 100
                const efficiency = (fuel / distance) * 100;
                fuelEfficiency.value = efficiency.toFixed(2);
                efficiencyNote.textContent = `* 基于上次加油(${lastOdometer}km)计算，行驶了${distance.toFixed(1)}km`;
                
            } catch (error) {
                console.error(`计算油耗失败: ${error.message}`);
                fuelEfficiency.value = '';
                efficiencyNote.textContent = '* 计算油耗时发生错误';
            }
        }
        
        // 过滤记录
        function filterRecords(filter) {
            try {
                // 清空搜索框
                const searchInput = document.getElementById('searchRecords');
                if (searchInput) {
                    searchInput.value = '';
                }
                
                loadRecords(filter);
            } catch (error) {
                showError('过滤记录失败: ' + error.message);
            }
        }
        
        // 设置激活的过滤器
        function setActiveFilter(filter) {
            try {
                const filterBtns = document.querySelectorAll('.filter-btn');
                filterBtns.forEach(btn => {
                    if (btn.id === `filter${filter.charAt(0).toUpperCase() + filter.slice(1)}`) {
                        btn.classList.add('active', 'bg-primary', 'text-white');
                        btn.classList.remove('bg-gray-200');
                    } else {
                        btn.classList.remove('active', 'bg-primary', 'text-white');
                        btn.classList.add('bg-gray-200');
                    }
                });
            } catch (error) {
                console.error(`设置过滤器时出错: ${error.message}`);
            }
        }
        
        // 获取当前激活的过滤器
        function getActiveFilter() {
            try {
                const activeFilter = document.querySelector('.filter-btn.active');
                const filter = activeFilter ? activeFilter.id.replace('filter', '').toLowerCase() : 'all';
                return filter;
            } catch (error) {
                console.error(`获取过滤器时出错: ${error.message}`);
                return 'all'; // 默认返回全部
            }
        }
        
        // 填充上次记录的里程
        async function populateLastOdometer() {
            try {
                const records = await getAllRecordsFromDB();
                if (records.length > 0) {
                    // 按时间戳排序，取最近的一条记录的里程（排除过路费记录）
                    const lastRecord = records
                        .filter(r => r.type !== 'toll' && r.odometer !== undefined)
                        .sort((a, b) => {
                            const timeA = a.timestamp || a.id;
                            const timeB = b.timestamp || b.id;
                            return timeB - timeA; // 降序排列
                        })[0];
                    
                    if (lastRecord) {
                        const odometerInput = document.getElementById('odometer');
                        if (odometerInput) {
                            odometerInput.value = lastRecord.odometer;
                        }
                    }
                }
            } catch (error) {
                console.error(`填充里程失败: ${error.message}`);
            }
        }
        
        // 计算统计数据
        async function calculateStats() {
            try {
                const records = await getAllRecordsFromDB();
                let fuelTotal = 0;
                let tollTotal = 0;
                let maintenanceTotal = 0;
                let monthTotal = 0;
                let totalEfficiency = 0;
                let efficiencyCount = 0;
                
                const today = new Date();
                const currentMonth = today.getMonth();
                const currentYear = today.getFullYear();
                
                // 筛选出所有加油记录并按日期排序（旧到新）
                const fuelRecords = records
                    .filter(r => r.type === 'fuel')
                    .sort((a, b) => new Date(a.date) - new Date(b.date));
                
                // 忽略首次加油记录，从第二条开始计算油耗
                if (fuelRecords.length >= 2) {
                    // 从第二条记录开始计算（索引1）
                    for (let i = 1; i < fuelRecords.length; i++) {
                        const currentRecord = fuelRecords[i];
                        const previousRecord = fuelRecords[i - 1];
                        
                        // 验证数据有效性
                        if (currentRecord.odometer > previousRecord.odometer && currentRecord.amount > 0) {
                            const distance = currentRecord.odometer - previousRecord.odometer;
                            const efficiency = (currentRecord.amount / distance) * 100;
                            totalEfficiency += efficiency;
                            efficiencyCount++;
                        }
                    }
                }
                
                // 按类型统计金额
                records.forEach(record => {
                    if (record.type === 'fuel') {
                        fuelTotal += record.total;
                    } else if (record.type === 'toll') {
                        tollTotal += record.total;
                    } else if (record.type === 'maintenance') {
                        maintenanceTotal += record.total;
                    }
                    
                    // 本月统计
                    const recordDate = new Date(record.date);
                    if (recordDate.getMonth() === currentMonth && recordDate.getFullYear() === currentYear) {
                        monthTotal += record.total;
                    }
                });
                
                // 计算平均油耗
                const avgEfficiency = efficiencyCount > 0 ? (totalEfficiency / efficiencyCount).toFixed(2) : '--';
                
                // 更新统计显示
                const fuelTotalStats = document.getElementById('fuelTotalStats');
                const tollTotalStats = document.getElementById('tollTotalStats');
                const maintenanceTotalStats = document.getElementById('maintenanceTotalStats');
                const monthTotalStats = document.getElementById('monthTotalStats');
                const totalRecordsStats = document.getElementById('totalRecordsStats');
                const avgFuelEfficiency = document.getElementById('avgFuelEfficiency');
                
                if (fuelTotalStats) fuelTotalStats.textContent = fuelTotal.toFixed(2) + '元';
                if (tollTotalStats) tollTotalStats.textContent = tollTotal.toFixed(2) + '元';
                if (maintenanceTotalStats) maintenanceTotalStats.textContent = maintenanceTotal.toFixed(2) + '元';
                if (monthTotalStats) monthTotalStats.textContent = monthTotal.toFixed(2) + '元';
                if (totalRecordsStats) totalRecordsStats.textContent = records.length;
                if (avgFuelEfficiency) avgFuelEfficiency.textContent = avgEfficiency + ' 升/百公里';
                
            } catch (error) {
                throw error;
            }
        }
        
        // 显示弹窗
        function showModal(modal, content) {
            try {
                if (!modal || !content) {
                    console.warn('弹窗元素缺失');
                    return;
                }
                
                modal.classList.remove('hidden');
                setTimeout(() => {
                    content.classList.remove('scale-95', 'opacity-0');
                    content.classList.add('scale-100', 'opacity-100');
                }, 10);
            } catch (error) {
                console.error(`显示弹窗时出错: ${error.message}`);
            }
        }
        
        // 关闭弹窗
        function closeModal(modal) {
            try {
                if (!modal) {
                    console.warn('弹窗元素缺失');
                    return;
                }
                
                const content = modal.querySelector('[id^="modal"]');
                if (!content) {
                    console.warn('弹窗内容元素缺失');
                    return;
                }
                
                content.classList.remove('scale-100', 'opacity-100');
                content.classList.add('scale-95', 'opacity-0');
                setTimeout(() => {
                    modal.classList.add('hidden');
                }, 300);
            } catch (error) {
                console.error(`关闭弹窗时出错: ${error.message}`);
            }
        }
        
        // 显示提示消息
        function showToast(message, type = 'success') {
            try {
                // 创建toast元素
                const toast = document.createElement('div');
                const bgColor = type === 'error' ? 'bg-danger' : 'bg-dark';
                toast.className = `fixed bottom-20 left-1/2 transform -translate-x-1/2 ${bgColor} text-white px-4 py-2 rounded-lg shadow-lg z-50 opacity-0 transition-all duration-300`;
                toast.textContent = message;
                document.body.appendChild(toast);
                
                // 显示toast
                setTimeout(() => {
                    toast.classList.remove('opacity-0');
                    toast.classList.add('opacity-90');
                }, 10);
                
                // 3秒后隐藏toast
                setTimeout(() => {
                    toast.classList.remove('opacity-90');
                    toast.classList.add('opacity-0');
                    setTimeout(() => {
                        document.body.removeChild(toast);
                    }, 300);
                }, 3000);
            } catch (error) {
                console.error('显示提示消息时出错:', error);
            }
        }
        
        // 显示错误消息
        function showError(message) {
            try {
                const errorContainer = document.getElementById('errorContainer');
                const errorMessage = document.getElementById('errorMessage');
                
                if (errorContainer && errorMessage) {
                    errorMessage.textContent = message;
                    errorContainer.classList.remove('hidden');
                    
                    // 5秒后自动隐藏
                    setTimeout(() => {
                        errorContainer.classList.add('hidden');
                    }, 5000);
                } else {
                    // 如果没有错误容器，使用toast
                    showToast(message, 'error');
                }
            } catch (error) {
                console.error('显示错误消息时出错:', error);
            }
        }
    </script>


    </body>
</html>